package com.cloudpivot.receivales;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSONObject;
import com.cloudpivot.receivales.meta.bsweaverdocws.DocAttachment;
import com.cloudpivot.receivales.meta.bsweaverdocws.DocInfo;
import com.cloudpivot.receivales.meta.bsweaverdocws.DocServiceLocator;
import com.cloudpivot.receivales.meta.bsweaverdocws.DocServicePortType;
import com.cloudpivot.receivales.meta.controller.SignFileController;
import com.cloudpivot.receivales.meta.domain.OAWFFile;
import com.cloudpivot.receivales.meta.domain.OAWFFileInfo;
import com.cloudpivot.receivales.meta.service.PvDocumentService;
import com.cloudpivot.receivales.meta.service.impl.FileHandleServiceImpl;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;

import javax.xml.rpc.ServiceException;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.*;

@SpringBootTest
class CloudpivotApplicationTestForMetaFile {

    @Value("${workorder.modepath}")
    private String MODEPATH;

    @Autowired
    private PvDocumentService pvDocumentService;

    @Autowired
    private FileHandleServiceImpl fileHandleService;

    @Autowired
    private SignFileController signFileController;


    @Test
    public void testFirstdoc() {
        try {
            File file = new File("/Users/kent/cloudpivot/docmode/sign.png");
            File inFile = new File("/Users/kent/cloudpivot/docmode/PFQMS.docx");
            InputStream inStream = new FileInputStream(inFile);

//          XWPFTemplate template = XWPFTemplate.compile("/Users/kent_1/cloudpivot/docmode/PFQMS.docx");

            List<Map<String, Object>> list = new ArrayList<>();
            for (int i = 0; i < 3; i++) {
                Map<String, Object> map = new HashMap<>();
                InputStream in = new FileInputStream(file);
                map.put("timeStr", "2022-07-08");
                map.put("signPic", in);
                list.add(map);
            }

            pvDocumentService.insertToDocLastForDocx(list, inStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testPdfEdit() {
        try {
            File inFile = new File("/Users/kent_1/cloudpivot/docmode/PFQMS.pdf");
            File signFile = new File("/Users/kent_1/cloudpivot/docmode/sign.png");
            InputStream modeFile = new FileInputStream(inFile);
            byte[] byteFile = IoUtil.readBytes(modeFile);

            List<Map<String, Object>> list = new ArrayList<>();
            for (int i = 0; i < 7; i++) {
                Map<String, Object> map = new HashMap<>();
                InputStream in = new FileInputStream(signFile);
                map.put("timeStr", "2022-09-30");
                map.put("signPic", in);
                list.add(map);
            }

//            pvDocumentService.insertToSignToPdf(list, byteFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试 file  转为pdf
     */
    @Test
    public void testFileToPdf() {
        try {
            File _inFile = new File("/Users/kent/cloudpivot/docmode/PFQMS.docx");
            FileInputStream fileInputStream = new FileInputStream(_inFile);
            byte[] buffer = new byte[(int) _inFile.length()];
            fileInputStream.read(buffer);
            fileInputStream.close();
            java.util.Base64.Encoder encoder = Base64.getEncoder();
            String _base64 = encoder.encodeToString(buffer);
            //上面不要
            //_base64为输入的内容 需转为File
            File inFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
            BufferedOutputStream bos=null;
            FileOutputStream fos=null;
            byte[] bytes = Base64.getDecoder().decode(_base64);
            fos = new FileOutputStream(inFile);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
            byte[] retByte=fileHandleService.fileToPdf(inFile,"docx");


            //生成测试文件 实际也不要
            File file = new File("/Users/kent/cloudpivot/docmode/out/222.pdf");
            FileOutputStream fos1 = new FileOutputStream(file);
            BufferedOutputStream bos1 = new BufferedOutputStream(fos1);
//            bos1.write(retByte);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Test
    public void testFileToPdfController() {
        try {
            OAWFFile oawfFile = new OAWFFile();
            oawfFile.setFilePath(3943);
            oawfFile.setFileBase64(convertToBase64("/Users/kent/cloudpivot/docmode/new1.docx"));
            oawfFile.setFileType("docx");
            oawfFile.setTitleName("测试推送");
            oawfFile.setFileName("测试用EHR文件");
            OAWFFileInfo oawfFileInfo = new OAWFFileInfo();
            oawfFileInfo.setIndex(0);
            oawfFileInfo.setSignBase64(convertToBase64("/Users/kent/cloudpivot/docmode/sign.png"));
            oawfFileInfo.setSignTime("2022-12-02");
            List<OAWFFileInfo> list = new ArrayList<>();
            list.add(oawfFileInfo);
            oawfFile.setSignInfo(list);
            List<OAWFFile> listMain = new ArrayList<>();
            listMain.add(oawfFile);

            signFileController.signFileFromOAWF(listMain);

            //生成测试文件 实际也不要
//            File file = new File("/Users/kent/cloudpivot/docmode/out/222.pdf");
//            FileOutputStream fos1 = new FileOutputStream(file);
//            BufferedOutputStream bos1 = new BufferedOutputStream(fos1);
//            bos1.write(retByte);

            System.out.println("ok");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 直接上传文件的 weaver的目录
     */
    @Test
    public void createDocToWeaver(){
        try {
            File file = new File("/Users/kent/cloudpivot/docmode/PFQMS.docx");
            DocServicePortType servicePortType = new DocServiceLocator().getDocServiceHttpPort(new URL("http://172.16.0.201/services/DocService"));

            String loginid = "sysadmin";
            String password = "biosan@2202";
            int logintype = 0;
            String ip = "172.16.0.201";
            String session = servicePortType.login(loginid, password, logintype, ip);
            DocAttachment da = new DocAttachment();
            da.setDocid(105052);
            da.setImagefileid(0);
            da.setFilecontent(convertToBase64("/Users/kent/cloudpivot/docmode/PFQMS-14采购管理程序ForTest.docx"));
            //da.setFilerealpath("upFile/test.doc");
            da.setIszip(0);
            da.setFilename(file.getName());//文档名称
            da.setIsextfile("1");
            da.setDocfiletype("3");
            da.setVersionDetail("testversion");
            da.setVersionId(110370);

            DocInfo doc = new DocInfo();//创建文档
            doc.setDoccreaterid(1);//创建人ID
            doc.setDoccreatertype(1);
            doc.setAccessorycount(1);
            doc.setMaincategory(1);//主目录id
            doc.setSubcategory(1);//分目录id
            doc.setSeccategory(3827);//子目录id //质量档案的测试目录
            doc.setOwnerid(1);
            doc.setId(105052);
//            doc.setDocStatus(0);//文档状态
            doc.setDocType(2);
            doc.setDocSubject(file.getName());//知识中文档的名称,一般与上面的文档名称一致即可
            doc.setDoccontent("内容见附件");//文档中html的内容
            doc.setAttachments(new DocAttachment[] { da });
            System.out.println("新文档id："+servicePortType.createDoc(doc, session));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void updateDocToWeaver(){
        try {
            File file = new File("/Users/kent/cloudpivot/docmode/PFQMS.docx");
            DocServicePortType servicePortType = new DocServiceLocator().getDocServiceHttpPort(new URL("http://172.16.0.201/services/DocService"));

            String loginid = "sysadmin";
            String password = "biosan@2202";
            int logintype = 0;
            String ip = "172.16.0.201";
            String session = servicePortType.login(loginid, password, logintype, ip);
            Integer docid = 105046;
            DocInfo doc = servicePortType.getDoc(docid,session);
            DocAttachment da1 = doc.getAttachments()[0];
            DocAttachment da = new DocAttachment();
            BeanUtils.copyProperties(da1,da);

            da.setImagefileid(0);
            da.setDocid(105046);
            da.setFilecontent(convertToBase64("/Users/kent/cloudpivot/docmode/PFQMS-14采购管理程序ForTest.docx"));
            da.setFilename("PFQMS-14采购管理程序ForTest4.docx");
            da.setIszip(1);
            da.setIsextfile("1");
            da.setDocfiletype("3");
            da.setVersionDetail("替换附件");

            doc.setDoccontent("内容见附件(有更新)-停用");
            doc.setDocarchivedate("2021-12-31");
            doc.setDoclastmoddate("2021-12-31");
            doc.setDoccreatedate("2021-12-31");
            doc.setDocSubject(file.getName()+"-停用");
            doc.setDocStatus(1);//文档中html的内容
            doc.setChilddoc(new int[]{105046});
            doc.setAttachments(new DocAttachment[] { da,da1 });
            System.out.println("更新文档："+servicePortType.updateDoc(doc, session));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void getDocToWeaver(){
        try {
            File file = new File("/Users/kent/cloudpivot/docmode/PFQMS.docx");
            DocServicePortType servicePortType = new DocServiceLocator().getDocServiceHttpPort(new URL("http://172.16.0.201/services/DocService"));

            String loginid = "sysadmin";
            String password = "biosan@2202";
            int logintype = 0;
            String ip = "172.16.0.201";
            String session = servicePortType.login(loginid, password, logintype, ip);

            DocInfo doc = servicePortType.getDoc(159461, session);
//            int count=servicePortType.getDocCount("159461");

            System.out.println("打印获取文件结果:--> "+doc);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void base64FileTest() {
        String path = "/Users/kent_1/cloudpivot/docmode/PFQMS-14采购管理程序ForTest.docx";
        String base64 = convertToBase64(path);
        System.out.println("---------------"+base64);
    }

    private String convertToBase64(String path) {
        try {
            File _inFile = new File(path);
            FileInputStream fileInputStream = new FileInputStream(_inFile);
            byte[] buffer = new byte[(int) _inFile.length()];
            fileInputStream.read(buffer);
            fileInputStream.close();
            Base64.Encoder encoder = Base64.getEncoder();
            String base64 = encoder.encodeToString(buffer);
            return base64;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static InputStream base64ToInputStream(String base64) {
        ByteArrayInputStream stream = null;
        try {
            byte[] bytes = Base64.getDecoder().decode(base64);
            stream = new ByteArrayInputStream(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stream;
    }


}
